package com.example.hospital.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.hospital.api.common.PageUtils;
import com.example.hospital.api.db.dao.DrugDao;
import com.example.hospital.api.db.dao.DrugNumDao;
import com.example.hospital.api.db.pojo.DrugEntity;
import com.example.hospital.api.db.pojo.DrugNumEntity;
import com.example.hospital.api.exception.HospitalException;
import com.example.hospital.api.service.DrugService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
@Slf4j
public class DrugServiceImpl implements DrugService {
    @Resource
    private DrugDao drugDao;

    @Resource
    private DrugNumDao drugNumDao;

    @Override
    public PageUtils searchByPage(Map param) {
        ArrayList<HashMap> list = null;
        long count = drugDao.searchCount(param);
        if (count > 0) {
            list = drugDao.searchByPage(param);
        } else {
            list = new ArrayList<>();
        }
        int page = MapUtil.getInt(param, "page");
        int length = MapUtil.getInt(param, "length");
        PageUtils pageUtils = new PageUtils(list, count, page, length);
        return pageUtils;
    }

    @Override
    public HashMap searchAllDrug() {
        ArrayList<HashMap> list = drugDao.searchAllDrug();
        LinkedHashMap map = new LinkedHashMap();
        return map;
    }

    @Override
    public void insert(Map param) {
        DrugEntity drugEntity = BeanUtil.toBean(param, DrugEntity.class);
        drugDao.insert(drugEntity);

        String drugid = drugEntity.getDrugid();
        String drugname = drugEntity.getDrugname();

        DrugNumEntity drugNumEntity = new DrugNumEntity();
        drugNumEntity.setDrugid(drugid);
        drugNumEntity.setDrugname(drugname);
        drugNumDao.insert(drugNumEntity);
    }

    @Override
    public HashMap searchAll() {
        HashMap map=drugDao.searchAll();
        return map;
    }

    @Override
    public HashMap searchById(int id) {
        HashMap map = drugDao.searchById(id);
        return map;
    }

    @Override
    @Transactional
    public void update(Map param) {
        drugDao.update(param);
    }

    @Override
    @Transactional
    public void deleteByIds(Integer[] ids) {
        long count = drugDao.searchDoctorCount(ids);
        if (count == 0) {
            drugDao.deleteByIds(ids);
        } else {
            throw new HospitalException("药品数量有余，无法删除记录");
        }
    }
}
